package com.example.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class Test {
    @Value("${server.port}")
    String port;

    @GetMapping("/test")
    public String test() {
        Cookie[] sessions = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getCookies();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        if (sessions != null) {
            for (Cookie cookie : sessions) {
                if (cookie.getName().equals("DONGQUN")) {
                    return "i am server" + port + "(已登录)" + "--domain " + cookie.getDomain() + " --path " + cookie.getPath() + " --name " + cookie.getName();
                }
            }
        }

        Cookie cookie1 = new Cookie("DONGQUN", "1234567890");
        response.addCookie(cookie1);
        return "i am server" + port + "(未登录)";
    }
}
